//
// Copyright 2019 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// Package util contains various helper functions
package util

import (
	"time"

	log "github.com/golang/glog"
	"golang.org/x/time/rate"
)

var rateLimiters = map[time.Duration]*rate.Limiter{}

func allowedToLog(interval time.Duration) bool {
	lim, ok := rateLimiters[interval]
	if !ok {
		lim = rate.NewLimiter(rate.Every(interval), 1)
		rateLimiters[interval] = lim
	}
	return lim.Allow()
}

// LogErrEveryNTime is a throttled logging function.
// At most 1 error can be logged every interval.
func LogErrEveryNTime(interval time.Duration, message ...interface{}) {
	if allowedToLog(interval) {
		log.Error(message...)
	}
}

// LogWarnEveryNTime is a throttled logging function.
// At most 1 warning can be logged every interval.
func LogWarnEveryNTime(interval time.Duration, message ...interface{}) {
	if allowedToLog(interval) {
		log.Warning(message...)
	}
}

// LogErrfEveryNTime is a throttled formatted logging function.
// At most 1 error can be logged every interval.
func LogErrfEveryNTime(interval time.Duration, format string, args ...interface{}) {
	if allowedToLog(interval) {
		log.Errorf(format, args...)
	}
}

// LogWarnfEveryNTime is a throttled formatted logging function.
// At most 1 warning can be logged every interval.
func LogWarnfEveryNTime(interval time.Duration, format string, args ...interface{}) {
	if allowedToLog(interval) {
		log.Warningf(format, args...)
	}
}
